package com.customization.huangwm.workflowNodeAction.SW003;

import com.alibaba.fastjson.JSONObject;
import com.customization.huangwm.utils.DBTools;
import com.customization.huangwm.utils.LogTool;
import com.engine.common.util.ServiceUtil;
import com.engine.workflow.entity.publicApi.PAResponseEntity;
import com.engine.workflow.entity.publicApi.ReqOperateRequestEntity;
import com.engine.workflow.entity.publicApi.WorkflowDetailTableInfoEntity;
import com.engine.workflow.publicApi.WorkflowRequestOperatePA;
import com.engine.workflow.publicApi.impl.WorkflowRequestOperatePAImpl;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.BaseBean;
import weaver.hrm.User;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestInfo;
import weaver.workflow.webservices.WorkflowRequestTableField;
import weaver.workflow.webservices.WorkflowRequestTableRecord;

import javax.print.DocFlavor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author Huangwm
 * @Date 2023-01-30
 * @Version 1.0
 * @Description TODO 物料領用節點后將根据明细1中的资产部门进行拆分合并，对同一个部门的发送给对应的部门资产负责人审批
 **/
public class AssetsApplicationStartV2 implements Action {
    private LogTool log = new LogTool("/log/SW003/huangwm/WfAction/AssetsApplicationStartV2", false);
    private DBTools dbTools = new DBTools();
    @Override
    public String execute(RequestInfo requestInfo) {
        String requestid = requestInfo.getRequestid();
        String nodeType = requestInfo.getRequestManager().getNodetype();
        String src = requestInfo.getRequestManager().getSrc();
        int creater = requestInfo.getRequestManager().getCreater();
        log.writeLog("物料申領流程創建后分解>>>" + requestid + ">>" + nodeType + ">>" + src);
        String tableName = requestInfo.getRequestManager().getBillTableName();
        String billid = requestInfo.getRequestManager().getBillid() + "";

        User user = requestInfo.getRequestManager().getUser();
        Map<String,String> maindata = new HashMap<>();
        Property[] properties = requestInfo.getMainTableInfo().getProperty();
        for(Property property : properties){
            maindata.put(property.getName(),property.getValue());
        }

        String wfid01 = new BaseBean().getPropValue("SW003", "wfid01");
        String table01 = new BaseBean().getPropValue("SW003", "table01");
        if(wfid01.isEmpty() || table01.isEmpty()){
            requestInfo.getRequestManager().setMessageid(requestid);
            requestInfo.getRequestManager().setMessagecontent("未获取到配置文件SW003中的wfid01或table01");
            return FAILURE_AND_CONTINUE;
        }

        RecordSet rs = new RecordSet();
        RecordSet rs2 = new RecordSet();
        rs2.execute("select distinct managerDep from "+tableName+"_dt1 where mainid="+billid);
        while (rs2.next()){
            List<Map<String,Object>> detaildata = new ArrayList<>();
            String managerDepid = rs2.getString("managerDep");
            rs.execute("select * from "+tableName+"_dt1 where mainid="+billid +" and managerDep="+managerDepid);
            while (rs.next()){
                String assetCode = rs.getString("assetCode");
                String assetName = rs.getString("assetName");
                String managerDep = rs.getString("managerDep");
                maindata.put("manageDep",managerDep);
                String isAsset = rs.getString("isAsset");
                String field1 = rs.getString("field1");//仓库
                String userid = rs.getString("userid");//使用人
                String depManager = rs.getString("depManager");
                int applicationQuantity = Double.valueOf(rs.getDouble("applicationQuantity")).intValue();
                //針對資產的物料一條條拆分插入
                if(isAsset.equals("0")){
                    for(int i=0;i<applicationQuantity;i++){
                        Map<String,Object> data = new HashMap<>();
                        data.put("assetCode",assetCode);
                        data.put("assetName",assetName);
                        data.put("managerDep",managerDep);
                        data.put("isAsset",isAsset);
                        data.put("applicationQuantity",1);
                        data.put("depManager",depManager);
                        data.put("reviewQuantity",1);
                        data.put("field1",field1);
                        data.put("userid",userid);
                        detaildata.add(data);
                    }
                }else{
                    Map<String,Object> data = new HashMap<>();
                    data.put("assetCode",assetCode);
                    data.put("assetName",assetName);
                    data.put("managerDep",managerDep);
                    data.put("isAsset",isAsset);
                    data.put("applicationQuantity",applicationQuantity);
                    data.put("depManager",depManager);
                    data.put("reviewQuantity",applicationQuantity);
                    data.put("field1",field1);
                    data.put("userid",userid);
                    detaildata.add(data);
                }
            }
            try {
                ReqOperateRequestEntity requestParam = new ReqOperateRequestEntity();
                //流程流转扩展参数
                Map <String,Object> otherParams = new HashMap<>();
                otherParams.put("isVerifyPer","0"); //不验证用户创建流程权限

                requestParam.setMainData(getFormMainData(maindata));
                requestParam.setDetailData(getFormDetailData(detaildata,table01));
                requestParam.setWorkflowId(Integer.parseInt(wfid01));
                requestParam.setRequestName(requestInfo.getDescription().replace("申請","審批"));
                requestParam.setOtherParams(otherParams);

                WorkflowRequestOperatePA operatePA = ServiceUtil.getService(WorkflowRequestOperatePAImpl.class);
                PAResponseEntity respose = operatePA.doCreateRequest(user,requestParam);
                log.writeLog(JSONObject.toJSONString(respose.getErrMsg()));
                log.writeLog(respose.getCode().getStatusCode()+"  "+respose.getCode().getMessage());
                if(respose.getCode().getStatusCode()>1){
                    requestInfo.getRequestManager().setMessageid(requestid);
                    requestInfo.getRequestManager().setMessagecontent(JSONObject.toJSONString(respose.getErrMsg()));
                    return FAILURE_AND_CONTINUE;
                }
            } catch (Exception e) {
                e.printStackTrace();
                requestInfo.getRequestManager().setMessageid(requestid);
                requestInfo.getRequestManager().setMessagecontent("觸發申請子流程異常;"+e.getMessage()+" detaildata>"+detaildata.size());
                return FAILURE_AND_CONTINUE;
            }
        }
        return SUCCESS;
    }

    /**
     * 主表数据
     * 附件上传 包含base64, http等
     * 包含浏览框数据，单行文本数据
     * @return
     */
    private List <WorkflowRequestTableField> getFormMainData(Map<String,String> maindata){
        List <WorkflowRequestTableField> mainFields = new ArrayList <>();

        //申请人
        WorkflowRequestTableField applicationUser = new WorkflowRequestTableField();
        applicationUser.setFieldName("applicationUser");
        applicationUser.setFieldValue(maindata.get("applicationUser"));
        applicationUser.setView(true);
        applicationUser.setEdit(true);
        mainFields.add(applicationUser);

        //申请部門
        WorkflowRequestTableField applicationDep = new WorkflowRequestTableField();
        applicationDep.setFieldName("applicationDep");
        applicationDep.setFieldValue(maindata.get("applicationDep"));
        applicationDep.setView(true);
        applicationDep.setEdit(true);
        mainFields.add(applicationDep);

        //申请日期
        WorkflowRequestTableField applicationDate = new WorkflowRequestTableField();
        applicationDate.setFieldName("applicationDate");
        applicationDate.setFieldValue(maindata.get("applicationDate"));
        applicationDate.setView(true);
        applicationDate.setEdit(true);
        mainFields.add(applicationDate);

        //備注
        WorkflowRequestTableField remake = new WorkflowRequestTableField();
        remake.setFieldName("remake");
        remake.setFieldValue(maindata.get("remake"));
        remake.setView(true);
        remake.setEdit(true);
        mainFields.add(remake);

        //默認數量
        WorkflowRequestTableField num0 = new WorkflowRequestTableField();
        num0.setFieldName("num0");
        num0.setFieldValue(maindata.get("num0"));
        num0.setView(true);
        num0.setEdit(true);
        mainFields.add(num0);

        //入職使用人
        WorkflowRequestTableField joinUser = new WorkflowRequestTableField();
        joinUser.setFieldName("joinUser");
        joinUser.setFieldValue(maindata.get("joinUser"));
        joinUser.setView(true);
        joinUser.setEdit(true);
        mainFields.add(joinUser);

        //相關附件
        WorkflowRequestTableField enclosure = new WorkflowRequestTableField();
        enclosure.setFieldName("enclosure");
        enclosure.setFieldValue(maindata.get("enclosure"));
        enclosure.setView(true);
        enclosure.setEdit(true);
        mainFields.add(enclosure);

        //主管理部门
        WorkflowRequestTableField manageDep = new WorkflowRequestTableField();
        manageDep.setFieldName("manageDep");
        manageDep.setFieldValue(maindata.get("manageDep"));
        manageDep.setView(true);
        manageDep.setEdit(true);
        mainFields.add(manageDep);

        log.writeLog(JSONObject.toJSONString(mainFields));
        return mainFields;
    }

    /**
     * 明细数据
     * @return
     */
    private List<WorkflowDetailTableInfoEntity> getFormDetailData(List<Map<String,Object>> detaildata,String table01){
        List<WorkflowDetailTableInfoEntity> details = new ArrayList<>();
        //明细信息
        WorkflowDetailTableInfoEntity detail2 = new WorkflowDetailTableInfoEntity();
        detail2.setTableDBName(table01);
        //明细行
        WorkflowRequestTableRecord[] detailRows = new WorkflowRequestTableRecord[detaildata.size()];
        WorkflowRequestTableField field = null;
        for(int i=0;i<detaildata.size();i++){
            //明细行字段数据
            Map<String,Object> data = detaildata.get(i);
            WorkflowRequestTableField[] rowDatas = new WorkflowRequestTableField[data.size()];
            log.writeLog(JSONObject.toJSONString(data));
            int index = 0;
            for (Map.Entry<String,Object> entry : data.entrySet()){
                //行字段数据
                field = new WorkflowRequestTableField();
                field.setFieldName(entry.getKey());
                field.setFieldValue(String.valueOf(entry.getValue()));
                field.setView(true);
                field.setEdit(true);
                rowDatas[index] = field;
                index ++;
            }
            WorkflowRequestTableRecord row = new WorkflowRequestTableRecord();
            row.setRecordOrder(0);
            row.setWorkflowRequestTableFields(rowDatas);
            detailRows[i] = row;
        }
        detail2.setWorkflowRequestTableRecords(detailRows);
        details.add(detail2);

        //log.writeLog(JSONObject.toJSONString(details));
        return details;
    }

}
